--
--  Terminate_AllAppDelegate.applescript
--  Terminate All
--
--  Created by Bernard Maltais on 10-06-14.
--  Copyright 2010 Bank of Canada. All rights reserved.
--

script Terminate_AllAppDelegate
	property parent : class "NSObject"
	
	on applicationWillFinishLaunching_(aNotification)
		-- Insert code here to initialize your application before any files are opened 
	end applicationWillFinishLaunching_
	
	on applicationShouldTerminate_(sender)
		-- Insert code here to do any housekeeping before your application quits 
		return current application's NSTerminateNow
	end applicationShouldTerminate_
	
	on killAll_(sender)
		
		--
		-- Get list of active users but you and root
		--
		
		try
			set moi to do shell script "whoami"
			set userslist to do shell script "ps -Ajc | grep launchd | tr -s ' ' | cut -d ' ' -f 1 | grep -v " & moi & " | grep -v root"
			
		on error errMsg number errorNumber
			display dialog "You are the only active user. Nothing to do!" as text buttons ["Quit"] default button "Quit" with icon caution
			
			quit
		end try
		
		--
		-- Convert output to proper list based on carriage return as the text delimiter
		--
		
		try
			
			set AppleScript's text item delimiters to return
			set theUserList to text items of userslist
			set AppleScript's text item delimiters to {""}
			
		on error errMsg number errorNumber
			display dialog "An error occured while enumerating users to kill. Error " & errorNumber as text buttons ["Continue"] default button "Continue" with icon caution
			
			quit
		end try
		
		--
		-- Kill all active users processes
		--
		
		repeat with theIndividualUser in theUserList
			
			--
			-- display dialog theIndividualUser
			--
			
			try
				
				do shell script "ps -Ajc | grep loginwindow | grep " & theIndividualUser & " | tr -s ' ' | cut -d ' ' -f 2 | xargs -n 1 sudo kill -9" with administrator privileges
				delay 1
				do shell script "ps -Ajc | grep " & theIndividualUser & " | tr -s ' ' | cut -d ' ' -f 2 | xargs -n 1 sudo kill -9" with administrator privileges
				
			on error errMsg number errorNumber
				display dialog "An error occured while killing " & theIndividualUser & " processes. Error " & errorNumber as text buttons ["Continue"] default button "Continue" with icon caution
			end try
			
		end repeat
		
		display dialog "All users where terminated!" as text buttons ["Astalavista"] default button "Astalavista" with icon caution
		
		quit
		
	end killAll_
	
end script